package com.javaspeak.algorithm.fibonacci.intuitivecache;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * @author John Dickerson
 *
 */
public class FibonacciGeneratorTwo {

    private static Map<Integer,BigInteger> fibonacciSequence =
        new HashMap<Integer,BigInteger>();

    static {
        fibonacciSequence.put( 1, BigInteger.ONE );
        fibonacciSequence.put( 2, BigInteger.ONE );
    }


    public static BigInteger getFibonnacci( int i ) {

        BigInteger result = fibonacciSequence.get( i );

        if ( result == null ){

            BigInteger previous = fibonacciSequence.get( i - 1);

            if ( previous == null ){

                previous = getFibonnacci( i - 1 );
                fibonacciSequence.put( i - 1, previous );
            }

            BigInteger beforePrevious = fibonacciSequence.get( i - 2 );

            result = previous.add( beforePrevious );
            fibonacciSequence.put( i, result );
        }

        return result;
    }
}
